import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {Modal, Form, Input, InputNumber, Select, DatePicker, Switch} from 'antd'
import MyUpload from '../MyUpload/index'

import {isPhone} from 'kuan-utils/src/validate'

const {RangePicker} = DatePicker
const {TextArea} = Input
const FormItem = Form.Item
const {Option} = Select

const normalFn = () => {
}

const formItemLayout = {
  labelCol: {
    xs: {span: 24},
    sm: {span: 6},
  },
  wrapperCol: {
    xs: {span: 24},
    sm: {span: 16},
  },
}

@Form.create()
class MyModal extends Component {
  static propTypes = {
    data: PropTypes.array.isRequired,
    visible: PropTypes.bool.isRequired,
    form: PropTypes.object.isRequired,
    title: PropTypes.string,
    onOk: PropTypes.func,
    onCancel: PropTypes.func,
  }

  static defaultProps = {
    title: '编辑',
    onOk: normalFn,
    onCancel: normalFn,
  }

  validatePhone = (rule, value, callback) => {
    if (!isPhone(value)) {
      return callback('请正确输入手机号')
    }
    callback()
  }

  handleSubmit = (e) => {
    e.preventDefault()
    const {form, onOk} = this.props
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        onOk(values)
      }
    })
  }

  // options => {} || []
  renderSelect = (options, message) => {
    if (Array.isArray(options)) {
      return (
        <Select placeholder={message}>
          {options.map(option => (
            <Option
              key={option.value || option.id}
              value={(option.value ? option.value.toString : '') || option.id.toString()}
            >{option.name}
            </Option>)
          )}
        </Select>
      )
    }
    return (
      <Select placeholder={message}>
        {Object.entries(options).map(([key, name]) => <Option key={key} value={key}>{name}</Option>
        )}
      </Select>
    )
  }

  renderItem = (type, options, message, placeholder, initialValue) => {
    const components = {
      Select: this.renderSelect(options, message),
      DatePicker: <DatePicker placeholder={placeholder || message}/>,
      RangePicker: <RangePicker/>,
      TextArea: <TextArea placeholder={placeholder || message} />,
      Switch: <Switch defaultChecked={initialValue} />,
      InputNumber: <InputNumber />,
      MyUpload: <MyUpload />
    }
    return components[type] || <Input placeholder={message}/>
  }

  renderFormItem = ({label, key, rules, type, options = [], initialValue, component, placeholder}) => {
    const {form} = this.props
    const {getFieldDecorator} = form
    const message = `请输入${label}`
    rules = rules || [{required: true, message}]
    if (type === 'phone') {
      rules.push({
        validator: this.validatePhone
      })
    }
    const config = {rules}
    if (!(initialValue === undefined || initialValue === null)) config.initialValue = initialValue
    // 自定义组件
    if (component) {
      return (
        <FormItem key={key} {...formItemLayout} label={label}>
          {getFieldDecorator(key, config)(
            component
          )}
        </FormItem>
      )
    }
    return (
      <FormItem key={key} {...formItemLayout} label={label}>
        {getFieldDecorator(key, config)(
          !type ? <Input placeholder={placeholder || message}/> :
            this.renderItem(type, options, message, placeholder, initialValue)
        )}
      </FormItem>
    )
  }
  render() {
    const {title, onCancel, data, visible} = this.props
    return (
      <Modal
        visible={visible}
        title={title}
        onOk={this.handleSubmit}
        onCancel={onCancel}
      >
        {visible &&
        <Form onSubmit={this.handleSubmit}>
          {data.map(item => this.renderFormItem(item))}
        </Form>}
      </Modal>
    )
  }
}

export default MyModal
